package org.meetunexpectedly.service.audit;

import com.qiniu.http.Client;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.util.StringMap;
import org.meetunexpectedly.constant.AuditStatus;
import org.meetunexpectedly.entity.json.BodyJson;
import org.meetunexpectedly.entity.json.ScoreJson;
import org.meetunexpectedly.entity.json.SettingScoreJson;
import org.meetunexpectedly.entity.response.AuditResponse;
import org.meetunexpectedly.entity.setting.Setting;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 视频审核服务
 * @Author: pupil
 * @Date: 2024/08/19 下午 2:29
 */
@Service
public class VideoAuditService extends AbstractAuditService<String, AuditResponse> {

    // 七牛云视频审核api
    private final static String videoUrl = "http://ai.qiniuapi.com/v3/video/censor";
    // 视频审核请求体模板
    private static String videoBody = "{\n" +
            "    \"data\": {\n" +
            "        \"uri\": \"${url}\",\n" +
            "        \"id\": \"video_censor_test\"\n" +
            "    },\n" +
            "    \"params\": {\n" +
            "        \"scenes\": [\n" +
            "            \"pulp\",\n" +
            "            \"terror\",\n" +
            "            \"politician\"\n" +
            "        ],\n" +
            "        \"cut_param\": {\n" +
            "            \"interval_msecs\": 5000\n" +
            "        }\n" +
            "    }\n" +
            "}";


    @Override
    public AuditResponse audit(String url) {
        AuditResponse auditResponse = new AuditResponse();
        auditResponse.setAuditStatus(AuditStatus.SUCCESS.num);

        // 判断是否开启审核
        if (!isNeedAudit()) {
            // 没有开启直接返回
            return auditResponse;
        }

        // 附加uuid
        url = appendUUID(url);

        String body = videoBody.replace("${url}", url); // 请求体
        String method = "POST"; // 请求模式

        // 获取token
        String token = qiNiuConfig.getAuditToken(videoUrl, method, body, contentType);
        // 设置请求头
        StringMap headers = new StringMap();
        headers.put("Host","ai.qiniuapi.com");
        headers.put("Content-Type",contentType);
        headers.put("Authorization",token);

        // 创建配置并设置文件存储的服务区域(
        Configuration cfg = new Configuration(qiNiuConfig.getRegion());
        Client client = new Client(cfg);

        try {
            Response response = client.post(videoUrl, body.getBytes(), headers, contentType);
            Map map = objectMapper.readValue(response.getInfo().split("\n")[2], Map.class);
            Object job = map.get("job");
            // 获取审核结果的请求链接
            url = "http://ai.qiniuapi.com/v3/jobs/video/"+job.toString();
            method = "GET";
            // 获取token
            token = qiNiuConfig.getAuditToken(url, method, null, null);
            // 设置请求头
            headers = new StringMap();
            headers.put("Host","ai.qiniuapi.com");
            headers.put("Authorization",token);

            while (true){
                Response response1 = client.get(url, headers);

                BodyJson bodyJson = objectMapper.readValue(response1.getInfo().split(" \n")[2], BodyJson.class);
                // 如果从七牛云获取到的审核结果的状态【status】不是 “FINISHED”，则不进行校验（audit）方法，而是等待 2 秒再去获取一次，知直到状态为 “FINISHED”
                if (bodyJson.getStatus().equals("FINISHED")){
                    // 从系统配置表获取 pulp politician terror的审核比例
                    Setting setting = settingService.getById(settingId);
                    // 根据审核策略(包含通过、人工和PASS的审核比例的json字符串)(获取SettingScoreJson
                    SettingScoreJson settingScoreRule = objectMapper.readValue(setting.getAuditPolicy(), SettingScoreJson.class);
                    List<ScoreJson> scoreJsonList = Arrays.asList(settingScoreRule.getManualScore(), settingScoreRule.getPassScore(), settingScoreRule.getSuccessScore());
                    auditResponse = audit(scoreJsonList, bodyJson);
                    return auditResponse;
                }
                Thread.sleep(2000L);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return auditResponse;
    }
}
